package com.sf.marathon.soul.core.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作类<br/>
 * some common method extract from common-langs3:StringUtils<br/>
 */
public class StringUtils {

    private static Pattern UPPER_CASE = Pattern.compile("[A-Z]");
    private static Pattern UNDER_SCORE = Pattern.compile("_");

    private StringUtils() {
    }

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    /**
     * 将首字母转为大写
     *
     * @param str
     * @return
     */
    public static String capitalize(String str) {
        int strLen;
        if (str != null && (strLen = str.length()) != 0) {
            char firstChar = str.charAt(0);
            return Character.isTitleCase(firstChar) ? str : (new StringBuilder(strLen)).append(Character.toTitleCase(firstChar)).append(str.substring(1)).toString();
        } else {
            return str;
        }
    }

    /**
     * 将首字母转为小写
     *
     * @param str
     * @return
     */
    public static String uncapitalize(String str) {
        int strLen;
        if (str != null && (strLen = str.length()) != 0) {
            char firstChar = str.charAt(0);
            return Character.isLowerCase(firstChar) ? str : (new StringBuilder(strLen)).append(Character.toLowerCase(firstChar)).append(str.substring(1)).toString();
        } else {
            return str;
        }
    }

    /**
     * 驼峰格式转下划线格式 如：testName test_name
     *
     * @param javeBeanStr
     * @return
     */
    public static String camelToUnderline(String javeBeanStr) {
        StringBuilder buf = new StringBuilder();
        Matcher m = UPPER_CASE.matcher(javeBeanStr);
//        while (m.find()) {
//            m.appendReplacement(buf, "_" + m.group(0));
//        }
//        m.appendTail(buf);
        return buf.toString().toLowerCase();
    }

    /**
     * 下划线格式转驼峰格式 如： test_name testName
     *
     * @param underLineStr
     * @return
     */
    public static String underlineToCamel(String underLineStr) {
        StringBuilder buf = new StringBuilder(underLineStr);
        Matcher mc = UNDER_SCORE.matcher(underLineStr);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            // 如果'_'为最后的字符,则直接退出循环,解决db2中'rownumber_'字符串数组越界问题
            if (position == underLineStr.length()) {
                break;
            }
            buf.replace(position - 1, position + 1, buf.substring(position, position + 1).toUpperCase());
        }
        return buf.toString();
    }

    /**
     * 重置stringBuilder的值
     *
     * @param sb
     * @param s
     */
    public static void resetStringBuilder(StringBuilder sb, String s) {
        sb.delete(0, sb.length());
        sb.append(s);
    }
}
